﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using AyuBookmark.Common.Interfaces;
using AyuBookmark.Common.Models;
using AyuBookmark.Common.Extensions;

namespace AyuBookmark.Common.Repositories
{
    /// <summary>
    /// 图片资源仓库实现
    /// </summary>
    public class ImageRepository : BaseRepository<Image, int>, IImageRepository
    {
        private const string TableName = "Images";
        private readonly string _imageStoragePath;

        public async Task<Image> GetByPathAsync(string path)
        {
            using var connection = await GetConnectionAsync();
            return await connection.QueryFirstOrDefaultAsync<Image>(
                $"SELECT * FROM {TableName} WHERE LocalPath = @path",
                new { path });
        }

        /// <inheritdoc />
        public async Task<int> CleanupOrphanedImagesAsync()
        {
            using var connection = await GetConnectionAsync();
            using var transaction = connection.BeginTransaction();

            try
            {
                // 1. 查询未被引用的图片
                var orphanedImages = await connection.QueryAsync<Image>(
                    $@"SELECT i.* FROM {TableName} i
                       LEFT JOIN {BookmarkTableName} b ON i.Id = b.ImageId
                       WHERE b.Id IS NULL");

                int deletedCount = 0;

                // 2. 删除图片文件和数据库记录
                foreach (var image in orphanedImages)
                {
                    // 删除物理文件
                    if (System.IO.File.Exists(image.LocalPath))
                    {
                        System.IO.File.Delete(image.LocalPath);
                    }

                    // 删除数据库记录
                    await connection.ExecuteAsync(
                        $"DELETE FROM {TableName} WHERE Id = @id",
                        new { id = image.Id },
                        transaction);

                    deletedCount++;
                }

                transaction.Commit();
                return deletedCount;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }

        private readonly string _connectionString;
        //private const string ImageTableName = "Images";
        private const string BookmarkTableName = "Bookmarks";
        /// <summary>
        /// 初始化图片仓库
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="imageStoragePath">图片存储物理路径</param>
        public ImageRepository(string connectionString, string imageStoragePath)
            : base(connectionString, TableName)
        {
            _imageStoragePath = imageStoragePath ?? throw new ArgumentNullException(nameof(imageStoragePath));

            // 确保存储目录存在
            if (!Directory.Exists(_imageStoragePath))
            {
                Directory.CreateDirectory(_imageStoragePath);
            }
            _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
        }

        #region IImageRepository 实现
        /// <inheritdoc />
        public async Task<Image> GetByHashAsync(string contentHash)
        {
            using var connection = await GetConnectionAsync();
            return await connection.QueryFirstOrDefaultAsync<Image>(
                $"SELECT * FROM {TableName} WHERE ContentHash = @contentHash",
                new { contentHash });
        }

        /// <inheritdoc />
        public async Task<string> SaveImageFileAsync(Stream imageStream, string fileExtension = ".jpg")
        {
            var tempFilePath = Path.GetTempFileName();
            try
            {
                // 保存到临时文件
                using (var fileStream = File.Create(tempFilePath))
                {
                    await imageStream.CopyToAsync(fileStream);
                }

                // 计算哈希
                var contentHash = ComputeFileSha256Hash(tempFilePath);

                // 检查是否已存在
                var existingImage = await GetByHashAsync(contentHash);
                if (existingImage != null)
                {
                    File.Delete(tempFilePath);
                    return existingImage.LocalPath;
                }

                // 生成存储路径
                var fileName = $"{contentHash}{fileExtension}";
                var storagePath = Path.Combine(_imageStoragePath, fileName);

                // 移动到正式存储位置
                File.Move(tempFilePath, storagePath);

                // 保存到数据库
                var image = new Image
                {
                    ContentHash = contentHash,
                    LocalPath = storagePath,
                    CreatedDate = DateTime.Now
                };

                await base.AddAsync(image);
                return storagePath;
            }
            finally
            {
                // 确保临时文件被删除
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }
            }
        }

        /// <inheritdoc />
      
        #endregion

        #region 重写基础方法
        /// <inheritdoc />
        public override async Task<bool> DeleteAsync(Image image)
        {
            // 先删除物理文件
            if (File.Exists(image.LocalPath))
            {
                File.Delete(image.LocalPath);
            }

            // 再删除数据库记录
            return await base.DeleteAsync(image);
        }

        /// <inheritdoc />
        public override async Task<bool> DeleteByIdAsync(int id)
        {
            // 先获取图片信息
            var image = await GetByIdAsync(id);
            if (image == null) return false;

            // 使用重写的DeleteAsync方法确保文件也被删除
            return await DeleteAsync(image);
        }
        #endregion

        #region 私有方法
        private static string ComputeFileSha256Hash(string filePath)
        {
            using var sha = System.Security.Cryptography.SHA256.Create();
            using var stream = File.OpenRead(filePath);
            var hash = sha.ComputeHash(stream);
            return BitConverter.ToString(hash).Replace("-", "").ToLower();
        }
        #endregion
    }
}